import axios from 'axios'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 1.创建axios的实例
const instance = axios.create({
    //根路径
    baseURL: 'http://bingjs.com:83',
    //超时时间
    timeout: 20000
})

//创建get请求
let get = async function (url, params) {
    let { data } =await instance.get(url, { params })
    return data
};

//创建post请求
let post =async function (url, params) {
    let {data} =await instance.post(url, params)
    return data
};

//将token保存到请求头
let setToken = function(){
    instance.defaults.headers.common['token'] = sessionStorage.getItem('token')
}

// 2.axios的拦截器
// 2.1.请求拦截的作用
instance.interceptors.request.use(config => {
    NProgress.start()
    return config
}, err => {
    NProgress.done()
    return err
})

// 2.2.响应拦截
instance.interceptors.response.use(res => {
    NProgress.done()
    return res
}, err => {
    NProgress.done()
    return err
})

export  {
    get,
    post,
    setToken
}

